﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CaptureView : MonoBehaviour
{
    public Image img_origin;
    public Image img_captureShow;
    public RawImage img_capture_rawTexture;
    public GameObject obj_captureShow;

    Texture2D screenShot = null;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            StartCoroutine(ScrrenCapture(OriginRect(img_origin.gameObject)));
        }
    }
    //截图
    IEnumerator ScrrenCapture(Rect rect)
    {
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        yield return new WaitForEndOfFrame();
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        //Texture->Sprite 给Image赋值
        Sprite sprite = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), Vector2.zero);
        img_captureShow.GetComponent<Image>().sprite = sprite;
        //给Raw Image赋值
        img_capture_rawTexture.texture = screenShot;
        //给物体材质赋值
        obj_captureShow.GetComponent<MeshRenderer>().material.mainTexture = screenShot;
    }
    //截图并保存(pc端)
    IEnumerator ScrrenCaptureAndSave(Rect rect, string path)
    {
        screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        yield return new WaitForEndOfFrame();
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();

        // 然后将这些纹理数据，成一个png图片文件
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.streamingAssetsPath + path;
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张图片: {0}", filename));

    }
    //获取源控件rect
    private Rect OriginRect(GameObject UIComponent)
    {
        Rect rect = new Rect();
        Vector3[] corners = new Vector3[4];
        //坐标的顺序是左下、左上、右上、右下
        UIComponent.GetComponent<RectTransform>().GetWorldCorners(corners);

        rect.x = corners[0].x;
        rect.y = corners[0].y;
        rect.width = corners[3].x - corners[0].x;
        rect.height = corners[1].y - corners[0].y;

        //Debug.Log("capture rect: " + rect);

        return rect;
    }

}
